package com.tian.hello.customerview

import android.content.Context
import android.os.Trace
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup

/**
 * Description: 可以定制上下摆放 ViewGroup
 * Author：skyTian
 * Time:2018/2/1
 * CopyRight:com,sky
 */
class CustomViewGroup constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {

    /**
     * 测量方法，预估整个viewGroup所占用的宽高
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//        Debug.startMethodTracing("jankStart");
//        Trace.beginSection("cViewMeasure");
        Log.d("CustomViewGroup", "onMeasure invoke")
        var measureWith = 0
        var measureHeight = 0
        //遍历子控件，对子控件进行测量
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            if (childView.visibility == GONE) continue
            //对子控件进行测量,只有先对子控件进行测量了，才能获取子控件的预估宽高
            measureChild(childView, widthMeasureSpec, heightMeasureSpec)
            measureHeight += childView.measuredHeight
            if (childView.measuredWidth > measureHeight) measureWith = childView.measuredWidth
        }

//        try {
//            Thread.sleep(1000);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //加上padding边值
        measureHeight += paddingBottom + paddingTop
        measureWith += paddingLeft + paddingRight

        //设置测量的值，这个值会在"摆放中(onLayout)"过程使用
        setMeasuredDimension(measureWith, measureHeight)
        printLifecycle("onMeasure")

//        Trace.endSection();
//        Debug.stopMethodTracing();
    }

    private fun printLifecycle(msg: String) {
        Log.i("CV", msg)
    }

    /**
     * 摆放方法,对控件内部的子控件进行摆放，比如水平排或竖直排。
     * <br></br>note ： l,t,r,b是控件在画布中的 起点和终点坐标
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        var t = t
        Trace.beginSection("cViewLayout")
        Log.d("CustomViewGroup", "onLayout invoke")
        for (i in 0 until childCount) {
            val v = getChildAt(i)
            if (v.visibility != GONE) {
                val childWidth = v.measuredWidth
                val childHeight = v.measuredHeight
                //开始摆放
                v.layout(l, t, l + childWidth, t + childHeight)
                //垂直方向累计坐标量
                t += childHeight
            }
        }
        Trace.endSection()
    }
}